package com.partyjoin.project.system.user.service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.jms.Destination;

import org.apache.activemq.command.ActiveMQQueue;
import org.apache.activemq.command.ActiveMQTopic;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.partyjoin.common.constant.Constants;
import com.partyjoin.common.constant.UserConstants;
import com.partyjoin.common.support.Convert;
import com.partyjoin.common.utils.CardUtil;
import com.partyjoin.common.utils.StringUtils;
import com.partyjoin.common.utils.security.ShiroUtils;
import com.partyjoin.framework.shiro.service.PasswordService;
import com.partyjoin.project.system.post.domain.Post;
import com.partyjoin.project.system.post.mapper.PostMapper;
import com.partyjoin.project.system.role.domain.Role;
import com.partyjoin.project.system.role.mapper.RoleMapper;
import com.partyjoin.project.system.user.domain.User;
import com.partyjoin.project.system.user.domain.UserPost;
import com.partyjoin.project.system.user.domain.UserRole;
import com.partyjoin.project.system.user.mapper.UserMapper;
import com.partyjoin.project.system.user.mapper.UserPostMapper;
import com.partyjoin.project.system.user.mapper.UserRoleMapper;
import com.partyjoin.project.tool.activemq.Producer;

/**
 * 用户 业务层处理
 * 
 * @author partyjoin
 */
@Service("userService")
public class UserServiceImpl implements IUserService
{
    @Autowired
    private UserMapper userMapper;

    @Autowired
    private RoleMapper roleMapper;

    @Autowired
    private PostMapper postMapper;

    @Autowired
    private UserPostMapper userPostMapper;

    @Autowired
    private UserRoleMapper userRoleMapper;

    @Autowired
    private PasswordService passwordService;

    /**
     * 根据条件分页查询用户对象
     * 
     * @param user 用户信息
     * 
     * @return 用户信息集合信息
     */
    @Override
    public List<User> selectUserList(User user)
    {
        return userMapper.selectUserList(user);
    }
    
    /**
     * 分页查询申请用户对象
     */
    @Override
    public List<User> selectProposerList(User user){
    	return userMapper.selectProposerList(user);
    }

    /**
     * 通过用户名查询用户
     * 
     * @param userName 用户名
     * @return 用户对象信息
     */
    @Override
    public User selectUserByLoginName(String userName)
    {
        return userMapper.selectUserByLoginName(userName);
    }

    /**
     * 通过手机号码查询用户
     * 
     * @param userName 用户名
     * @return 用户对象信息
     */
    @Override
    public User selectUserByPhoneNumber(String phoneNumber)
    {
        return userMapper.selectUserByPhoneNumber(phoneNumber);
    }

    /**
     * 通过邮箱查询用户
     * 
     * @param email 邮箱
     * @return 用户对象信息
     */
    @Override
    public User selectUserByEmail(String email)
    {
        return userMapper.selectUserByEmail(email);
    }

    /**
     * 通过用户ID查询用户
     * 
     * @param userId 用户ID
     * @return 用户对象信息
     */
    @Override
    public User selectUserById(Long userId)
    {
        return userMapper.selectUserById(userId);
    }

    /**
     * 通过用户ID删除用户
     * 
     * @param userId 用户ID
     * @return 结果
     */
    @Override
    public int deleteUserById(Long userId)
    {
        // 删除用户与角色关联
        userRoleMapper.deleteUserRoleByUserId(userId);
        // 删除用户与岗位表
        userPostMapper.deleteUserPostByUserId(userId);
        return userMapper.deleteUserById(userId);
    }
    
    /**
     * 账号激活
     */
    public int proposerAccept(Long userId){
    	User user = selectUserById(userId);
    	//置为申请人角色
    	Long[] roleIds = {Constants.PROPOSER_ROLE_ID};
    	user.setRoleIds(roleIds);
    	insertUserRole(user);
    	return userMapper.proposerAccept(userId);
    }

    /**
     * 批量删除用户信息
     * 
     * @param ids 需要删除的数据ID
     * @return 结果
     */
    @Override
    public void deleteUserByIds(String ids) throws Exception
    {
        Long[] userIds = Convert.toLongArray(ids);
        for (Long userId : userIds)
        {
            if (User.isAdmin(userId))
            {
                throw new Exception("不允许删除超级管理员用户");
            }
        }
        userMapper.deleteUserByIds(userIds);
    }

    /**
     * 保存用户信息
     * 
     * @param user 用户信息
     * @return 结果
     */
    @Override
    public int saveUser(User user)
    {
        int count = 0;
        Long userId = user.getUserId();
        if (StringUtils.isNotNull(userId))
        {
            user.setUpdateBy(ShiroUtils.getLoginName());
            // 修改用户信息
            count = updateUser(user);
            // 删除用户与角色关联
            userRoleMapper.deleteUserRoleByUserId(userId);
            // 新增用户与角色管理
            insertUserRole(user);
/*            // 删除用户与岗位关联
            userPostMapper.deleteUserPostByUserId(userId);
            // 新增用户与岗位管理
            insertUserPost(user);*/

        }
        else
        {
            user.randomSalt();
            user.setPassword(passwordService.encryptPassword(user.getLoginName(), user.getPassword(), user.getSalt()));
            user.setCreateBy(ShiroUtils.getLoginName());
            // 新增用户信息
            count = userMapper.insertUser(user);
/*            // 新增用户岗位关联
            insertUserPost(user);*/
            // 新增用户与角色管理
            insertUserRole(user);
        }
        return count;
    }
    
    /**
     * 用户注册
     */
    @Override
    public int register(User user){
    	int count = 0;
        user.setDeptId(getDeptByCollege(user.getCollege()));
    	user.randomSalt();
    	//置为未激活状态
    	user.setStatus(Constants.ACCOUNT_NONACTIVATE);
			try {
				user.setAge((int)CardUtil.getCarInfo(user.getIdCardNo()).get("age"));
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			//发送激活邮件请求到activemq
//	        Destination destination = new ActiveMQQueue("邮件队列");
//			Destination destination = new ActiveMQTopic("邮件主题模式");
//	        Map<String, String> info = new HashMap<String, String>();
//	        info.put("username", user.getUserName());
//	        info.put("loginname", user.getLoginName());
//	        info.put("password", user.getPassword());
//	        info.put("email", user.getEmail());
//	        producer.sendMessage(destination, (JSONObject.toJSON(info)).toString()); 
    	user.setPassword(passwordService.encryptPassword(user.getLoginName(), user.getPassword(), user.getSalt()));
    	count = userMapper.insertUser(user);
    	
    	return count;
    }
    
    /**
     * 根据学院选取部门
     */
    public Long getDeptByCollege(String collegeId){
    	Long deptId = null;
        switch(collegeId){
        case "1":
             deptId = (119l);
             break;
        case "2":
        	deptId = (122L);
            break;
        case "3":
        	deptId = (126L);
            break;
        case "4":
        	deptId = (131L);
            break;
        case "5":
        	deptId = (135L);
            break;
        case "6":
        	deptId = (138L);
            break;
        case "7":
        	deptId = (140L);
            break;
        case "8":
        	deptId = (143L);
            break;
        case "9":
        	deptId = (147L);
            break;
        case "10":
        	deptId = (149L);
            break;
        }
    return deptId;
    }

    /**
     * 修改用户信息
     * 
     * @param user 用户信息
     * @return 结果
     */
    @Override
    public int updateUser(User user)
    {
        return userMapper.updateUser(user);
    }

    /**
     * 修改用户密码
     * 
     * @param user 用户信息
     * @return 结果
     */
    @Override
    public int resetUserPwd(User user)
    {
        user.randomSalt();
        user.setPassword(passwordService.encryptPassword(user.getLoginName(), user.getPassword(), user.getSalt()));
        return updateUser(user);
    }

    /**
     * 新增用户角色信息
     * 
     * @param user 用户对象
     */
    public void insertUserRole(User user)
    {
        // 新增用户与角色管理
        List<UserRole> list = new ArrayList<UserRole>();
        for (Long roleId : user.getRoleIds())
        {
            UserRole ur = new UserRole();
            ur.setUserId(user.getUserId());
            ur.setRoleId(roleId);
            list.add(ur);
        }
        if (list.size() > 0)
        {
            userRoleMapper.batchUserRole(list);
        }
    }

    /**
     * 新增用户岗位信息
     * 
     * @param user 用户对象
     */
    public void insertUserPost(User user)
    {
        // 新增用户与岗位管理
        List<UserPost> list = new ArrayList<UserPost>();
        for (Long postId : user.getPostIds())
        {
            UserPost up = new UserPost();
            up.setUserId(user.getUserId());
            up.setPostId(postId);
            list.add(up);
        }
        if (list.size() > 0)
        {
            userPostMapper.batchUserPost(list);
        }
    }

    /**
     * 校验用户名称是否唯一
     * 
     * @param loginName 用户名
     * @return
     */
    @Override
    public String checkLoginNameUnique(String loginName)
    {
        int count = userMapper.checkLoginNameUnique(loginName);
        if (count > 0)
        {
            return UserConstants.USER_NAME_NOT_UNIQUE;
        }
        return UserConstants.USER_NAME_UNIQUE;
    }
    
    /**
     * 校验身份证号是否唯一
     */
    @Override
    public String checkIdCardNoUnique(String idCardNo){
    	int count = userMapper.checkIdCardNoUnique(idCardNo);
    	if(count > 0){
    		return UserConstants.USER_IDCARDNO_NOT_UNIQUE;
    	}
    	return UserConstants.USER_IDCARDNO_UNIQUE;
    }

    /**
     * 校验用户名称是否唯一
     *
     * @param phonenumber 用户名
     * @return
     */
    @Override
    public String checkPhoneUnique(User user)
    {
        if (user.getUserId() == null)
        {
            user.setUserId(-1L);
        }
        Long userId = user.getUserId();
        User info = userMapper.checkPhoneUnique(user.getPhonenumber());
        if (StringUtils.isNotNull(info) && StringUtils.isNotNull(info.getUserId())
                && info.getUserId().longValue() != userId.longValue())
        {
            return UserConstants.USER_PHONE_NOT_UNIQUE;
        }
        return UserConstants.USER_PHONE_UNIQUE;
    }

    /**
     * 校验email是否唯一
     *
     * @param email 用户名
     * @return
     */
    @Override
    public String checkEmailUnique(User user)
    {
        if (user.getUserId() == null)
        {
            user.setUserId(-1L);
        }
        Long userId = user.getUserId();
        User info = userMapper.checkEmailUnique(user.getEmail());
        if (StringUtils.isNotNull(info) && StringUtils.isNotNull(info.getUserId())
                && info.getUserId().longValue() != userId.longValue())
        {
            return UserConstants.USER_EMAIL_NOT_UNIQUE;
        }
        return UserConstants.USER_EMAIL_UNIQUE;
    }

    /**
     * 查询用户所属角色组
     * 
     * @param userId 用户ID
     * @return 结果
     */
    @Override
    public String selectUserRoleGroup(Long userId)
    {
        List<Role> list = roleMapper.selectRolesByUserId(userId);
        StringBuffer idsStr = new StringBuffer();
        for (Role role : list)
        {
            idsStr.append(role.getRoleName()).append(",");
        }
        if (StringUtils.isNotEmpty(idsStr.toString()))
        {
            return idsStr.substring(0, idsStr.length() - 1);
        }
        return idsStr.toString();
    }
    
    /**
     * 查询用户所属角色组id
     * 
     * @param userId 用户ID
     * @return 结果
     */
    @Override
    public String selectUserRoleIds(Long userId)
    {
        List<Role> list = roleMapper.selectRolesByUserId(userId);
        StringBuffer idsStr = new StringBuffer();
        for (Role role : list)
        {
            idsStr.append(role.getRoleId()).append(",");
        }
        if (StringUtils.isNotEmpty(idsStr.toString()))
        {
            return idsStr.substring(0, idsStr.length() - 1);
        }
        return idsStr.toString();
    }

    /**
     * 查询用户所属岗位组
     * 
     * @param userId 用户ID
     * @return 结果
     */
    @Override
    public String selectUserPostGroup(Long userId)
    {
        List<Post> list = postMapper.selectPostsByUserId(userId);
        StringBuffer idsStr = new StringBuffer();
        for (Post post : list)
        {
            idsStr.append(post.getPostName()).append(",");
        }
        if (StringUtils.isNotEmpty(idsStr.toString()))
        {
            return idsStr.substring(0, idsStr.length() - 1);
        }
        return idsStr.toString();
    }

    /**
     * 账号驳回
     */
	@Override
	public int proposerNotAccept(Long userId) {
        // 删除用户与角色关联
        userRoleMapper.deleteUserRoleByUserId(userId);
		return userMapper.proposerNotAccept(userId);
	}
	
	/**
	 * 根据条件分页查询党员用户对象
	 */
	@Override
	public List<User> selectMemberList(User user){
		return userMapper.selectMemberList(user);
	}

	/**
	 * 根据条件分页查询入党申请用户对象
	 */
	@Override
	public List<User> selectPartyJoin(User user) {
		return userMapper.selectPartyJoin(user);
	}

	/**
	 * 查询申请对象信息（已激活的）
	 */
	@Override
	public User selectProposer(Long userId) {
		User user = userMapper.selectProposer(userId);
		Long roleId = userRoleMapper.selectRoleIdByUserId(userId);
		user.setRoleIds(new Long[]{roleId});
		return user;
	}
	
	/**
	 * 查询积极分子后备人选
	 * @param user
	 * @return
	 */
	public List<User> selectActivistList(User user){
		return userMapper.selectActivistList(user);
	}

	/**
     * 获取需要进行发展积极分子的申请对象（已谈话，且递交入党申请书满6个月）
     */
	@Override
	public List<User> selectProposerToActivist(Long deptId) {
		List<User> userList = userMapper.selectProposerToActivist(deptId);
//		List<User> userLists = new ArrayList<User>();
//		//挑选身份为申请人的用户
//		for(User u : userList){
//			String roleIds = selectUserRoleIds(u.getUserId());
//			if(roleIds.equals("2")){
//				userLists.add(u);
//			}
//		}
		return userList;
	}

    /**
     * 获取需要进行发展对象的申请对象
     */
    @SuppressWarnings("unchecked")
	@Override
    public List<User> selectDevelopmentList(User user){
        return userMapper.selectDevelopmentList(user);
    }

    /**
     * 通过部门编号查询用户
     */
	@Override
	public List<User> selectUserByDeptId(Long deptId) {
		return userMapper.selectUserByDeptId(deptId);
	}

	/**
	 * 消除指定用户角色
	 */
	@Override
	public int removeUserRole(Long userId, Long roleId) {
		return userRoleMapper.removeUserRole(userId, roleId);
	}


	@Override
	public List<User> selectActivistToDevelopment(Long deptId) {
		List<User> userList = userMapper.selectActivistToDevelopment(deptId);
		return userList;
	}

	@Override
	public List<User> selectDevelopmentToPrepare(Long deptId) {
		List<User> userList = userMapper.selectDevelopmentToPrepare(deptId);
		List<User> userLists = new ArrayList<User>();
		//挑选身份为发展对象的用户
		for(User u : userList){
			String roleIds = selectUserRoleIds(u.getUserId());
			if(roleIds.equals("4")){
				userLists.add(u);
			}
		}
		return userLists;
	}

	@Override
	public List<User> selectPrepareToOfficial(Long deptId) {
		List<User> userList = userMapper.selectPrepareToOfficial(deptId);
		//挑选身份为预备党员的用户
		return userList;
	}
	
	/**
	 * 查询预备党员对象列表
	 */
	public List<User> selectPrepareList(User user){
		return userMapper.selectPrepareList(user);
	}

	/**
	 * 查询正式党员对象列表
	 */
	@Override
	public List<User> selectOfficialList(User user) {
		return userMapper.selectOfficialList(user);
	}

	/**
     * 获取需要进行预备党员预审的发展对象用于添加会议时下拉列表
     */
	@Override
	public List<User> selectDevelopmentToExamine(Long userDeptId) {
		return userMapper.selectDevelopmentToExamine(userDeptId);
	}

	/**
     * 通过部门编号查询管理员用户信息
     */
	@Override
	public List<User> selectAdminByDeptId(Long deptId) {
		return userMapper.selectAdminByDeptId(deptId);
	}
}
